package com.sk.seckilldemo.service;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀订单超时检查定时任务
 * */
@Component
@RequiredArgsConstructor
public class OrderTimeoutChecker {
    private final RedisTemplate<String,Object> redisTemplate;
    private final OrderService orderService;

    /**
     * 每分钟检查以此超时订单
     * */
    @Scheduled(cron = "0 * * * * ?")
    public void checkTimeoutOrders(){
        // 1. 扫描即将超时的订单
        Set<String> orderKeys = redisTemplate.keys("order:timeout:*");

        if(orderKeys==null||orderKeys.isEmpty()){
            return;
        }

        // 2. 处理每个超时的订单
        for(String key : orderKeys){
            String orderNo = key.substring("order:timeout:".length());

            //获取剩余时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if(expire!=null&&expire<=0){
                //已超时，处理订单
                orderService.processOrderTimeout(orderNo);
            }
        }
    }
}
